
# Create your tests here.

# class Abc():
#     def __init__(self):
#         pass
#     def func(self):
#         print(123)
#     def func1(self):
#         try:
#             self.func()
#         except:
#             return self.func()
#
# abc = Abc()
#
# abc.func1()


# def func(stats,phone):
#     if phone:
#         number = phone[0:len(stats)]  # 110,111,112
#         for i in stats: # 1,2,3
#             if number:
#                 print(i,number[0])
#                 phone.remove(number[0])
#                 number.pop(0)
#         func(stats,phone)
#     return
#
#
# seats_list = [1,2,3,4]
#
# phone_list = [110,111,112,113,114,115,116,117,118,119]
#
# func(seats_list,phone_list)


# def reconsitution_data(*args,**kwargs):
#     dict_data = {}
#     for k,v in kwargs.items():
#         if v:
#             dict_data[k] = v
#     return dict_data

# print(reconsitution_data(a="1",b="2",c=""))

# url = "http://39.102.47.215:2024/Batch_Call/queues/"
# headers = {
#     "Content-Type":"application/json;charset=utf-8",
#     "Accept":"application/json"
# }
# data = {
#     "queueId":"Q2008"
# }
# res = requests.delete(url=url,headers=headers,data=json.dumps(data)).json()
#
# print(res)

# a = {"a":"123456","b":"654321"}
# json_data = json.dumps(a,ensure_ascii=False)
# print(json_data)
# b = [{"a":"123456","b":"654321"}]
# json_data = json.dumps(b,ensure_ascii=False)
# print(json_data)
#
# c = {'bcsId': '2', 'friendlyName': 'testTask', 'priority': '10', 'leads': [{'tel': '13389545453', 'udata': '马菲菲电话测试'}, {'tel': '16619980636', 'udata': '电话测试'}], 'beginTime': '11', 'endTime': '', 'userCli': '02860695190', 'ccr': '100', 'state': '2'}
# d = {'bcsId': '9', 'friendlyName': '马菲菲测试', 'priority': '20', 'leads': [{'tel': 13389545453, 'udata': '马菲菲'}, {'tel': 17610572690, 'udata': '胜'}], 'beginTime': '', 'endTime': '', 'userCli': '', 'ccr': '100', 'state': '2'}
#


# a = ["00:01:00","00:02:00"]
# b = "00:03:00"
#
# def func(object_list):
#     r = 0
#     for i in object_list:
#         h, m, s = i.strip().split(':')
#
#         c = int(h)*3600 + int(m)*60 + int(s)
#         r += c
#
#     return r
#
# q1 = func(a)
#
# m, s = divmod(q1, 60)
# h, m = divmod(m, 60)
# print ("%02d:%02d:%02d" % (h, m, s))

# a = "12:20:00-21:00:00"
#
# b = ''.join(a.split('-')[0].split(':')[0:2]) + '-' +  ''.join(a.split('-')[-1].split(':')[0:2])
#
# c = b.split('-')[0][0:2] + ':' + b.split('-')[0][2:4] + ':' + '00' + '-' + b.split('-')[-1][0:2] + ':' + b.split('-')[-1][2:4] + ':' + '00'
#
# print(c)

# b = round(0 / 0 * 100,2)
# print(b)
import base64
from datetime import datetime

import redis
import pymysql
import json
import requests
from operator import itemgetter

def connect_redis(db):
    try:
        # r = redis.Redis(host='r-2zed2mpeqshup0fiaq.redis.rds.aliyuncs.com', db=db, password='hqMsezH3ZDPkFuC8',
        #                 port=6379, decode_responses=True)
        r = redis.Redis(host='r-2zed2mpeqshup0fiaqpd.redis.rds.aliyuncs.com', db=db, password='hqMsezH3ZDPkFuC8',
                        port=6379, decode_responses=True)
        return r
    except:
        return 500



# 外呼数据库
def connect_outbound():
    """数据库连接"""
    try:
        db = pymysql.connect(
            host='39.97.216.76',
            port=3306,
            user='zb_outbound',
            password='zb_outbound',
            db='zb_outbound',
            charset='utf8'
        )

        return db
    except Exception as e:
        print(e)
        return 500

# crm数据库
def connect_crm():
    try:
        db = pymysql.connect(
            # 连接数据库
            host='39.97.216.76',
            port=3306,
            user='zb_crm_test',
            password='zb_crm_test',
            db='zb_crm_test',
            charset='utf8',
        )
        return db
    except Exception as e:
        print(e)
        return 500

# BOSS数据库
def connect_boss():
    try:
        db = pymysql.connect(
            # 连接备份数据库
            # host='172.17.122.150',
            host='39.97.216.76',
            port=3306,
            user='zb_boss_test',
            password='zb_boss_test',
            db='zb_boss_test',
            charset='utf8',
        )
        return db
    except Exception as e:
        print(e)
        return 500

# cc对接测试鉴权参数
def authentication():
    account = "e6beac74632e4783b5e6f68da8fa508d"
    app_sid = "17aa086feb8844798120a129ea615402"
    password = "31dad1da9e214e698a9d6b0996e6573b"
    return {"account":account,"app_sid":app_sid,"password":password}

# 为空的值不添加至字典
def reconsitution_data(data):
    dict_data = {}
    for k,v in data.items():
        if v:
            dict_data[k] = v
    return dict_data

# 查询班组名称
def query_group_name(queue_id):
    # 连接数据库
    connect = connect_crm()
    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        sql = "select group_name from zb_team_or_group where id='%s'" % queue_id
        cursor.execute(sql)
        data_list = cursor.fetchall()
        if not data_list:
            return ""
        connect.close()
        cursor.close()
        return data_list[0].get('group_name','')
    except Exception as e:
        print('查询班组名称异常',str(e))
        return

# 查询模板名称
def query_template_name(template_id):
    if not template_id:
        return ""
    # 连接CRM数据库
    connect = connect_crm()
    cursor = connect.cursor()
    try:
        sql = "select template_name from zb_template where id=%s" % template_id
        cursor.execute(sql)
        data = cursor.fetchone()
        connect.close()
        cursor.close()
        if not data:
            return ""
        return data[0]
    except Exception as e:
        print('查询模板名称异常',str(e))
        return 500

print(query_template_name(template_id=""))

# 查询队列下关联的所有坐席
def query_relation_seats(queue_number):
    # 连接数据库
    connect = connect_outbound()
    cursor = connect.cursor()
    try:
        sql = "select seats_number from zb_queues_relation where queue_number='%s'"%queue_number
        cursor.execute(sql)
        data = cursor.fetchall()
        data_list = []
        for i in data:
            data_list.append(i[0])
        connect.close()
        cursor.close()
        return {"code":200,"msg":"查询成功","data":{"queue_number":queue_number,"seats_number":data_list}}
    except Exception as e:
        print('查询队列下关联的所有坐席异常',str(e))
        return {"code":500,"msg":"系统繁忙","error":str(e)}

# 查询所有坐席状态
def seats_status(*args, **kwargs):
    # 坐席工号
    agentNo = kwargs.get('agentNo', '')
    # 坐席组id
    agentNo_id = kwargs.get('agentNo_id', '')
    try:
        account = authentication().get('account', '')
        app_sid = authentication().get('app_sid', '')
        password = authentication().get('password', '')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/AgentStatus/query".format(account,
                                                                                                                app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "agentNo": agentNo,
            "queueId": agentNo_id
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        return res
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}

# 查询所有坐席状态
def seats_status1(agentNo):
    try:

        account = authentication().get('account', '')
        app_sid = authentication().get('app_sid', '')
        password = authentication().get('password', '')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/AgentStatus/query".format(account,
                                                                                                                app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "agentNo": agentNo,
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        # print(res)
        return res
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}


def pager(*args, **kwargs):
    """
    个人自定义分页器，方便适用于数据量不大时的分页器
    传参方式
    调用mff_pager(data=[{"xxx":"xxx"},{"xxx":"xxx"}],page=1,page_size=10)
    传参为不定长参数，data为需要切割的数据，page为第几页，page_size为每页数据量
    """
    if int(kwargs['page']) == 0:
        kwargs['page'] = 1

    if kwargs['page_size'] == '':
        kwargs['page_size'] = 10
    # 计算从什么位置开始切(当前页-1,再*一页的数据个数)
    data_start = (int(kwargs['page']) - 1) * (int(kwargs['page_size']))

    # 计算切到什么位置结束
    data_end = int(kwargs['page']) * int(kwargs['page_size'])
    # 查询 切片操作(已切完的数据)
    goods = kwargs['data'][data_start:data_end]

    return goods

def retrieve_task1(*args,**kwargs):
    bcsId = kwargs.get('bcsId','')
    taskId = kwargs.get('taskId','')
    try:
        account = authentication().get('account','')
        app_sid = authentication().get('app_sid','')
        password = authentication().get('password','')
        url = "https://api.zbtx.cc:8624/2019-08-08/Accounts/{}/Applications/{}/ccpaas/batchcallTasks/retrieve".format(
            account, app_sid)
        token = "Basic " + str(base64.b64encode((account + ":" + password).encode('utf-8')), "utf-8")
        headers = {
            "Authorization": token,
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
        data = {
            "bcsId": bcsId,
            "taskId": taskId
        }
        res = requests.post(url=url, headers=headers, data=json.dumps(reconsitution_data(data))).json()
        if res['statusCode'] == "00000":
            return {"code": 200, "msg": "查询成功","data":res['data']}
        else:
            return {"code": 403, "msg": str(res['statusMsg'])}
    except Exception as e:
        return {"code": 10001, "msg": "请检查传入参数", "error": str(e)}

def query_account_all():
    # 连接boss数据库
    connect1 = connect_boss()
    cursor1 = connect1.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        sql1 = "select identify from zb_account where status='0'"
        cursor1.execute(sql1)
        account_list = cursor1.fetchall()
        if not account_list:
            return []

        return account_list
    except:
        return []


def retrieve_task(account):
    if not account:
        return
    start_time = datetime.now()
    # 连接外呼数据库
    connect = connect_outbound()
    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        account_tag = account
        # 查询每个企业下的任务
        sql2 = "select * from zb_task where account_tag='%s'"%account_tag
        cursor.execute(sql2)
        data_list = cursor.fetchall()
        if not data_list:
            return
        # cursor.close()
        # connect.close()
        r = connect_redis(19)
        r.delete(account_tag)
        L = []
        count_number = 1
        for data in data_list:
            # 查询服务ID
            sql3 = "select server_id from zb_server where queue_id='%s'"%data.get('queue_id','')
            cursor.execute(sql3)
            server_id = cursor.fetchall()
            if not server_id:
                server_id = ''
            else:
                server_id = server_id[0].get('server_id','')
            data['server_id'] = server_id
            # 查询班组名称
            group_name = query_group_name(data.get('group_id', ''))
            data['group_name'] = group_name
            # 查询模板名称
            data['template_name'] = query_template_name(data.get('template_id', ''))
            # 查询任务进度
            residue_data = retrieve_task1(bcsId=server_id, taskId=data.get('task_id'))
            # 线索总数
            data['call_count'] = residue_data.get('data', [{'totalLeads': 0}])[0].get('totalLeads', 0)
            # 剩余线索
            data['residue_call'] = residue_data.get('data', [{'leftLeads': 0}])[0].get('leftLeads', 0)
            # 已完成
            stocks = int(data['call_count']) - int(data['residue_call'])
            data['stocks'] = stocks
            # 进度
            try:
                data['schedule'] = str(
                    round(stocks / int(residue_data.get('data', [{'totalLeads': 0}])[0].get('totalLeads', 0)) * 100,
                          2)) + '%'
            except:
                data['schedule'] = '0.0%'
            # 创建时间
            data['create_time'] = str(data.get('create_time', ''))
            # 当前并发
            data['ccr_now'] = 0
            seats_list = query_relation_seats(data.get('queue_id', ''))
            seats_number_list = seats_list['data'].get('seats_number', [])
            # 坐席总数
            data['seats_count'] = len(seats_number_list)
            # 有效时间/小时
            work_time = data.get('work_time', '')
            data['work_time'] = work_time.split('-')[0][0:2] + ':' + work_time.split('-')[0][
                                                                     2:4] + ':' + '00' + '-' + \
                                work_time.split('-')[-1][0:2] + ':' + work_time.split('-')[-1][2:4] + ':' + '00'
            # 空闲坐席
            idle = 0
            for seats in seats_number_list:
                S = seats_status(agentNo=seats)
                data1 = S.get('data', [])
                if data1:
                    if data1[0].get('callState', '') == 'idle' and data1[0].get('sipStatus', '') == '1' and \
                            data1[0].get('workStatus', '') == '1':
                        idle += 1
            data['leisure_seats'] = idle
            L.append(data)

            r.hset(account_tag, str(count_number), json.dumps(data))
            count_number += 1
        connect.close()
        cursor.close()
        end_time = datetime.now()

        return L
    except Exception as e:
        return


def func():
    r = connect_redis(19)
    r.hset('wait_task', '1', json.dumps({'project': 'india', 'total_size': '15.8 MB'}))
    return

# retrieve_task()

def retrieve_task2(*args,**kwargs):
    account_tag = kwargs.get('account_tag', '')
    page = kwargs.get('page', 1)
    page_size = kwargs.get('page_size', 20)
    r = connect_redis(19)

    L = []
    for k in r.hkeys(account_tag):
            d = r.hget(account_tag, k)
            # print(json.loads(d))
            L.append(json.loads(d))
    if L:
        L.sort(key=itemgetter('create_time'), reverse=True)
        count = len(L)
        pager_data = pager(page=page, page_size=page_size, data=L)
        return {"code":200,"msg":"查询成功","total":count,"data":pager_data}
    else:
        return {"code": 200, "msg": "查询成功", "total": 0, "data": []}

# print(retrieve_task2(account_tag="62193abab55611eb",page=1,page_size=10))

# def run():
#     while True:
#         retrieve_task()
        # time.sleep(5)

# run()

# if __name__ == '__main__':
#     # 实例化
#     scheduler = BlockingScheduler()
#     scheduler.add_job(run, 'interval', seconds=10)
#     # 执行
#     try:
#         scheduler.start()
#     except Exception as e:
#         print(e)


from  multiprocessing import Pool
import os, time, random

def fun1(name):
    print('Run task %s (%s)...' % (name, os.getpid()))
    start = time.time()
    time.sleep(random.random() * 3)
    end = time.time()
    print('Task %s runs %0.2f seconds.' % (name, (end - start)))

def query_account_data(*args,**kwargs):
    account_id = kwargs.get('account_tag','')
    page = kwargs.get('page', 1)
    page_size = kwargs.get('page_size', 10)
    # 连接数据库
    connect = connect_outbound()
    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        sql = "select * from zb_task where account_tag='%s'" % account_id
        cursor.execute(sql)
        data_list = cursor.fetchall()
        count = len(data_list)
        if not data_list:
            return [],count
        data_list.sort(key=itemgetter('create_time'), reverse=True)
        pager_data = pager(page=page, page_size=page_size, data=data_list)
        connect.close()
        cursor.close()
        return pager_data,count
    except:
        return []

def query_task(data):
    # 连接外呼数据库
    connect = connect_outbound()
    cursor = connect.cursor(cursor=pymysql.cursors.DictCursor)
    # data_list = kwargs.get('data_list',[])
    # count = kwargs.get('count',0)
    # L = []
    # 查询服务ID
    sql3 = "select server_id from zb_server where queue_id='%s'" % data.get('queue_id', '')
    cursor.execute(sql3)
    server_id = cursor.fetchall()
    if not server_id:
        server_id = ''
    else:
        server_id = server_id[0].get('server_id', '')
    data['server_id'] = server_id
    # 查询模板名称
    data['template_name'] = query_template_name(data.get('template_id', ''))
    # 查询班组名称
    group_name = query_group_name(data.get('group_id', ''))
    data['group_name'] = group_name
    residue_data = retrieve_task1(bcsId=server_id, taskId=data.get('task_id'))
    # 线索总数
    data['call_count'] = residue_data.get('data', [{'totalLeads': 0}])[0].get('totalLeads', 0)
    # 剩余线索
    data['residue_call'] = residue_data.get('data', [{'leftLeads': 0}])[0].get('leftLeads', 0)
    # 已完成
    stocks = int(data['call_count']) - int(data['residue_call'])
    data['stocks'] = stocks
    # 进度
    try:
        data['schedule'] = str(
            round(stocks / int(residue_data.get('data', [{'totalLeads': 0}])[0].get('totalLeads', 0)) * 100,
                  2)) + '%'
    except:
        data['schedule'] = '0.0%'
    # 创建时间
    data['create_time'] = str(data.get('create_time', ''))
    # 当前并发
    data['ccr_now'] = 0
    seats_list = query_relation_seats(data.get('queue_id', ''))
    seats_number_list = seats_list['data'].get('seats_number', [])
    # 坐席总数
    data['seats_count'] = len(seats_number_list)
    # 有效时间/小时
    work_time = data.get('work_time', '')
    data['work_time'] = work_time.split('-')[0][0:2] + ':' + work_time.split('-')[0][2:4] + ':' + '00' + '-' + \
                        work_time.split('-')[-1][0:2] + ':' + work_time.split('-')[-1][2:4] + ':' + '00'
    # 空闲坐席
    idle = 0
    for seats in seats_number_list:
        S = seats_status(agentNo=seats)
        data1 = S.get('data', [])
        if data1:
            if data1[0].get('callState', '') == 'idle' and data1[0].get('sipStatus', '') == '1' and data1[0].get(
                    'workStatus', '') == '1':
                idle += 1
    data['leisure_seats'] = idle
    return data



def run(*args,**kwargs):
    try:
        account_tag = kwargs.get('account_tag','')
        if not account_tag:
            return {"code":403,"msg":"企业标识为必须参数"}
        page = kwargs.get('page',1)
        page_size = kwargs.get('page_size',10)
        start_time = datetime.now()
        pool = Pool(5)  # 创建一个5个进程的进程池
        # seats_list = ["3001", "3002", "3003", "3004", "3005"] * 100
        data_list = query_account_data(account_tag=account_tag,page=page,page_size=page_size)
        count = data_list[-1]
        pool_list = []
        for i in data_list[0]:
            pool_list.append(pool.apply_async(func=query_task, args=(i,)))
        pool.close()
        pool.join()
        L = []
        for data in pool_list:
            if data.get():
                L.append(data.get())
        print('结束测试', datetime.now() - start_time)
        return {"code":200,"msg":"查询成功","total":count,"data":L}
    except Exception as e:
        return {"code":500,"msg":"系统繁忙","error":str(e)}

def run1():
    pass

print(run(account_tag="123",page=1,page_size=20))

# print(query_account_data(account_tag="09cccf04966411eb"))

# if __name__=='__main__':
#     while True:
#         run()
#         time.sleep(10)
    # "0:00:03.930884"

# seats_list = ["3001","3002","3003","3004","3005"] * 100
# start_time = datetime.now()
# for i in seats_list:
#     seats_status1(i)
# print('结束测试',datetime.now() - start_time)
# "0:00:16.690804"
